﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace MyLinqHelper
{
    public class Criteria
    {
        private List<Criterion> listCriterion;

        public Criteria()
        {
            listCriterion = new List<Criterion>();
        }

        public Criteria(Criterion criterion)
            : this()
        {
            this.listCriterion.Add(criterion);
        }

        public void Add(Criterion criterion)
        {
            this.listCriterion.Add(criterion);
        }

        internal Expression GetExpression<TEntity>(IQueryable<TEntity> queryableData)
        {
            if (this.listCriterion.Count == 0)
                return null;
            ParameterExpression pe = Expression.Parameter(typeof(TEntity), "o");
            if (this.listCriterion.Count == 1)
                return this.listCriterion[0].GetExpression<TEntity>(pe);
            Expression kq = this.listCriterion[0].GetExpression<TEntity>(pe);
            for (int i = 1; i < this.listCriterion.Count; i++)
            {
                kq = Expression.And(kq, this.listCriterion[i].GetExpression<TEntity>(pe));
            }
            MethodCallExpression whereCallExpression = Expression.Call(
                typeof(Queryable),
                "Where",
                new Type[] { queryableData.ElementType },
                queryableData.Expression,
                Expression.Lambda<Func<TEntity, bool>>(kq, new ParameterExpression[] { pe }));
            return whereCallExpression;
        }
    }
}
